<!-- eslint-disable vue/no-template-shadow -->
<template>
  <div class="dashboard-container">
    <div class="filter-container">
      <el-row :gutter="10" style="width:100%;margin-bottom:10px">
        <el-col :span="3">
          <el-input
            v-model="listQuery.tid"
            placeholder="系统单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.trade_code"
            placeholder="提单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.trade_code_real"
            placeholder="真实提单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.first_waybill_no"
            placeholder="主运单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-input
            v-model="listQuery.waybill_no"
            placeholder="从运单号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="3">
          <el-select
            v-model="listQuery.is_pay"
            style="width:100%"
            placeholder="是否支付"
            clearable
            @change="reloadList"
          >

            <el-option
              label="是"
              :value="true"
            />
            <el-option
              label="否"
              :value="false"
            />
          </el-select>
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="listQuery.created"
            style="width: 100%;"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>
        <el-col :span="10">
          <div style="display:flex;margin-top:10px">
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="reloadList"
            >搜索</el-button>
            <el-button
              class="filter-item"
              type="primary"
              @click="getNumBatch()"
            >
              取末端单号
            </el-button>
            <el-button
              class="filter-item"
              type="primary"
              @click="regeneration()"
            >
              预生成子母件
            </el-button>
          </div>
        </el-col>
      </el-row>
    </div>
    <div style="padding:0 20px">

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        height="calc(100vh - 260px)"
        style="width: 100%;"
        size="mini"
        border
        tooltip-effect="dark"
        :header-cell-style="{ background: '#eaf1fd', color: '#333' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="40"
        />
        <el-table-column
          label="系统订单号"
          width="200px"
          fixed
        >
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.tid }}</span>
            </div>
          </template>

        </el-table-column>
        <el-table-column
          label="提单号"
          width="200px"
        >
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.trade_code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="真实提单号"
          width="200px"
        >
          <template slot-scope="{ row }">
            <div>
              <span v-if="row.order && row.order.customs_affairs">{{ row.order.customs_affairs.code }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="主运单号"
          width="150px"
        >
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.order.first_waybill_no }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="从运单号"
          width="150px"
        >
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.waybill_no }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column
          label="订单总数"
          prop="count"
          min-width="180px"
        />
        <el-table-column
          label="商品总数"
          prop="total_num"
          width="150px"
        />
        <el-table-column
          label="总价格"
          prop="total_amount"
          min-width="150px"
        />
        <el-table-column
          label="总重量"
          prop="total_weight"
          min-width="150px"
        />
        <el-table-column
          label="状态"
          width="100px"
        >
          <template slot-scope="{ row }">
            <div>
              <el-tag :type="row.order.status == 102?'info':row.order.status == 103?'':row.order.status == 104?'success':'danger'">{{ row.order.status == 102?'待取号':row.order.status == 103?'已取号':row.order.status == 104?'已发货':'已废弃' }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="订单标识"
          width="160px"
        >
          <template slot-scope="{ row }">
            <div>
              <el-tag style="margin-right:10px" :type="row.order.label_data.is_error?'success':'info'">异</el-tag>
              <el-tag style="margin-right:10px" :type="row.order.label_data.is_collect?'success':'info'">揽</el-tag>
              <el-tag style="margin-right:10px" :type="row.order.label_data.is_complete?'success':'info'">完</el-tag>
              <el-tooltip v-if="row.order.error" class="item" effect="dark" :content="row.order.error" placement="top">
                <el-tag style="margin-right:10px;cursor:pointer" :type="row.order.label_data.is_pay?'success':'info'">支</el-tag>
              </el-tooltip>
              <el-tag v-else style="margin-right:10px;" :type="row.order.label_data.is_pay?'success':'info'">支</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="客户唛头"
          prop="order.receiver.user_mark"
          width="150px"
        />
        <el-table-column
          label="收件人"
          prop="order.receiver.name"
          width="140px"
        />

        <el-table-column
          label="收件人电话"
          prop="currency"
          width="140px"
        >
          <template slot-scope="{ row }">
            <div>
              <span>+{{ row.order.receiver.area_code }}</span>
              <span>{{ row.order.receiver.mobile }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="收件人地址"
          prop="currency"
          width="300px"
        >
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.order.receiver.nation }}</span>
              <span>{{ row.order.receiver.province }}</span>
              <span>{{ row.order.receiver.city }}</span>
              <span>{{ row.order.receiver.district }}</span>
              <span>{{ row.order.receiver.detailed }}</span>

            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="收件人邮编"
          prop="order.receiver.postcode"
          width="140px"
        />
        <el-table-column
          label="创建时间"
          prop="created"
          width="140px"
        />
        <el-table-column
          label="操作"
          align="right"
          min-width="350"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              size="mini"
              type=""
              @click="cheack(row)"
            >
              编辑
            </el-button>

            <el-button
              size="mini"
              type=""
              @click="toChildList(row.tid)"
            >
              订单列表详情
            </el-button>
            <el-button
              v-if="row.order.status == 104 && !row.order.label_data.is_pay"
              type="primary"
              @click="payOrder(row)"
            >
              提交支付
            </el-button>
            <el-button
              v-if="!row.order.second_waybill_no"
              size="mini"
              type="primary"
              @click="getNum(row)"
            >
              取末端单号
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <Detial :detial="detial" :ismother="is_mother" :status="status" :visible="visible" @update="closeDraw" @reload="reloadList" />
    <el-dialog
      title="取末端订单号"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        快递公司:
        <el-select
          v-model="company_code"
          style="width:80%"
          placeholder="请选择快递公司"
          clearable
        >
          <el-option
            v-for="(item,index) in CourierList"
            :key="index"
            :label="item.company_name"
            :value="item.company_code"
          />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitNum">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="批量取末端单号"
      :visible.sync="dialogGetNumBatch"
      width="500px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        <el-progress :percentage="((getNumBatchSucNum + getNumBatchErrNum) / selectList.length * 100).toFixed()" />

        <div style="font-size: 16px; margin-top: 15px;">
          共 {{ selectList.length }} 单，成功 {{ getNumBatchSucNum }} 单，失败 {{ getNumBatchErrNum }} 单
        </div>
        <div v-if="getNumBatchErrList.length > 0" style="font-size: 16px; margin-top: 15px;">
          <el-alert
            v-for="(item,index) in getNumBatchErrList"
            :key="index"
            :title="item.msg + ' X ' +item.num"
            :closable="false"
            style="margin-top: 10px;"
            type="error"
            show-icon
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogGetNumBatch = false;dialogVisible = false;getList()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="预生成子母件"
      :visible.sync="regenerationVisible"
      width="500px"
      :before-close="handleClose"
    >
      <div style="padding: 20px;display:flex;align-items:center">
        <div style="width:60px">提单号:</div>
        <el-input
          v-model="trade_code"
          placeholder="请输入提单号"
          clearable
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="regenerationVisible = false">取 消</el-button>
        <el-button type="primary" @click="regenerationSubmit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { orderMotherList, motherGetSecondWaybillNo, motherListUnpack, motherListCreate, pushPay } from '@/api/order/index'
import { listCourier } from '@/api/base/express'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Detial from './components/orderDetial.vue'

export default {
  name: 'Dashboard',
  components: {
    Pagination,
    Detial
  },
  data() {
    return {
      is_mother: false,
      regenerationVisible: false,
      trade_code: '',
      loadingExcel: false,
      dialogVisible: false,
      dialogGetNumBatch: false, // 批量取末端单号弹窗
      data_arr: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        tid: '',
        trade_code: '',
        waybill_no: '',
        is_pay: '',
        first_waybill_no: '',
        created: [],
        trade_code_real: ''
      },
      visible: false,
      status: 1,
      id: '',
      detial: {},
      row: {},
      CourierList: [],
      company_code: '',
      selectList: [],
      getNumBatchSucNum: 0, // 批量取末端单号-成功的数量
      getNumBatchErrNum: 0, // 批量取末端单号-失败的数量
      getNumBatchErrList: [], // 批量取末端单号-失败原因
      submitGetNumType: 1 // 默认为单个取末端单号， 2 为批量
    }
  },
  computed: {
  },
  created() {
    this.getList()
    this.getlistCouriers()
  },
  methods: {
    payOrder(row) {
      var that = this
      this.$confirm('支付此订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        pushPay({
          tids: [row.tid]
        }).then(res => {
          that.$message({
            type: 'success',
            message: res.msg
          })
          that.getList()
        })
      }).catch(() => {

      })
    },
    toChildList(tid) {
      this.$router.push({
        path: '/order/childList',
        query: {
          tid: tid
        }
      })
    },
    handleSelectionChange(val) {
      this.selectList = val
    },
    getlistCouriers() {
      listCourier({
        limit: 1000,
        status: 1,
        is_mother: 1
      }).then(res => {
        this.CourierList = res.data.data
      })
    },
    getNum(row) {
      this.dialogVisible = true
      this.company_code = ''
      this.row = row
      this.submitGetNumType = 1 // 单次操作取末端单号
    },
    getNumBatch() {
      if (!this.selectList.length) {
        this.$message({
          type: 'error',
          message: '请选择要取号的订单'
        })
        return
      }
      this.dialogVisible = true
      this.company_code = ''
      this.submitGetNumType = 2 // 批量操作
      this.getNumBatchSucNum = 0
      this.getNumBatchErrNum = 0
      this.getNumBatchErrList = []
    },
    handleClose() {
      this.dialogVisible = false
      this.regenerationVisible = false
    },
    submitNum() {
      if (this.submitGetNumType === 2) {
        // 批量
        this.dialogGetNumBatch = true
        this.selectList.forEach(value => {
          motherGetSecondWaybillNo({
            tid: value.tid,
            company_code: this.company_code
          }).then(res => {
            if (res.sub_code === 'success') {
              // 成功
              this.getNumBatchSucNum++
            } else {
              this.getNumBatchErrNum++
              const index = this.existErrorMsg(res.msg)
              if (index === false) {
                this.getNumBatchErrList.push({ msg: res.msg, num: 1 })
              } else {
                this.getNumBatchErrList[index].num++
              }
            }
          })
        })
      } else {
        motherGetSecondWaybillNo({
          tid: this.row.tid,
          company_code: this.company_code
        }).then(res => {
          this.$message({
            type: 'success',
            message: res.msg
          })
          this.dialogVisible = false
          this.getList()
        })
      }
    },
    existErrorMsg(msg) {
      if (this.getNumBatchErrList.length <= 0) {
        return false
      }
      let flag = false
      this.getNumBatchErrList.forEach((item, index) => {
        if (item.msg === msg) {
          flag = index
        }
      })
      return flag
    },
    closeDraw() {
      this.visible = false
    },
    addNews() {
      this.status = 1
      this.visible = true
    },
    edit(row) {
      this.detial = { ...row.order }
      this.status = 2
      this.visible = true
    },
    cheack(row) {
      this.detial = { ...row.order }
      this.status = 1
      this.is_mother = true
      this.visible = true
    },
    reloadList() {
      this.listQuery.page = 1
      this.visible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      orderMotherList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.count
        this.listLoading = false
      })
    },
    // 打开预生成弹框
    regeneration() {
      this.trade_code = ''
      this.regenerationVisible = true
    },
    getRegenerationPage() {
      return new Promise((resolve, reject) => {
        // 获取页数
        motherListUnpack({
          'trade_code': this.trade_code,
          'page': 1,
          'limit': 10
        }).then(res => {
          resolve(res.data.last_page)
        }).catch(() => {
          this.loadingExcel.close()
        })
      })
    },
    regenerationList(index) {
      return new Promise((resolve, reject) => {
        // 获取页数
        motherListUnpack({
          'trade_code': this.trade_code,
          'page': index,
          'limit': 10
        }).then(res => {
          resolve('')
        })
      })
    },
    getRegenerationPageCreate() {
      motherListCreate({
        'trade_code': this.trade_code
      }).then(res => {
        if (res.data.is_exist_data) {
          this.getRegenerationPageCreate()
        } else {
          this.loadingExcel.close()
          this.$message.success('执行完毕')
          this.regenerationVisible = false
          this.getList()
        }
      })
    },
    // 确定生成预子母件
    async regenerationSubmit() {
      this.loadingExcel = this.$loading({
        lock: true,
        text: '执行中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const last_page = await this.getRegenerationPage()
      if (last_page !== 1) {
        for (let index = 2; index <= last_page; index++) {
          await this.regenerationList(index)
        }
      }
      this.getRegenerationPageCreate()
    }
  }
}
</script>
<style scoped>
.filter-container{
  padding:20px 20px 10px;
}
.upload-demo{
  margin: 20px 0 10px;
}
</style>
